package com.example.shiro.controller;

import com.example.shiro.mapper.UserMapper;
import com.example.shiro.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @Autowired
    UserMapper userMapper;

    @RequestMapping({"/","/index"})
    public String toIndex(Model model){
        model.addAttribute("msg","hello,Shiro");
        return "index";
    }
    @GetMapping("/user/add")
    public String userAdd(){
        return "user/add";
    }

    @GetMapping("/user/update")
    public String userUpdate(){
        return "user/update";
    }

    @GetMapping("/toLogin")
    public String login(){
        return "login";
    }

    @GetMapping("/data")
    @ResponseBody
    public User data(){
        User name = userMapper.queryUserByName("diyi");
        return name;
    }


    @RequestMapping("/login")
    public String login(String username,String password,Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try{
            subject.login(token); //执行登录方法，如果没有异常说明就ok了
            return "index";
        }
        catch (UnknownAccountException e){ //用户名不存在
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){ //密码不存在
            model.addAttribute("msg","密码错误");
            return "login";
        }

    }

    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "未经授权无法访问";
    }
}
